#!/bin/sh

pghome="/opt/var/pgsql"
pgdata="$pghome/data"
pgver="$pghome/8.2"
pgdumpground="$pgver/dump"

# create postgres user in /etc/passwd if it's not there
if grep -q ^postgres /etc/group; then
    echo There already is a postgres group on the system.
else
    echo -n "No postgres group found, creating postgres group ... "
    cat >>/etc/group <<EOF
postgres::31:
EOF
    cp /etc/group /share/hdd/conf/
    echo ok
fi

if grep -q ^postgres /etc/passwd; then
    echo There already is a postgres user on the system.
else
    echo -n "No postgres user found, creating postgres user ... "
    cat >>/etc/passwd <<EOF
postgres:x:31:31:PostgreSQL:$pghome:/bin/sh
EOF
    cp /etc/passwd /share/hdd/conf/
    echo ok
fi

mkdir -p $pghome
chown postgres:postgres $pghome

mkdir -p $pgdumpground
chown -R postgres:postgres $pgver

# initdb if not done before
dbinited=0
if [ -d $pgdata ]; then
    echo The $pgdata directory already exists
else
    echo "Initialize database ... "
    /opt/bin/coreutils-su - postgres -c "/opt/bin/initdb -D $pgdata"
    [ -f $pgdata/PG_VERSION ] && echo "... database initialization done"
    dbinited=1
fi

# compatibility check and start db
/opt/etc/init.d/S98postgresql

if [ "$dbinited." = "1." -a -n "`pidof postmaster`" ]; then
    echo "Now database server is ready, you can test the connection by:"
    echo "	# su - postgres"
    echo "	$ /opt/bin/psql template1"
    echo "To allow access from other user, see http://www.postgresql.org/docs/8.2/interactive/sql-createuser.html"
    echo "To allow access from network, see http://developer.postgresql.org/docs/postgres/runtime-config.html#RUNTIME-CONFIG-CONNECTION"
fi
